package top.timestreet.xmsk.base.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import top.timestreet.xmsk.base.pojo.SearchPage;
import top.timestreet.xmsk.qu.boot.QuSearchPageBoot;
import top.timestreet.xmsk.w23txt.boot.W23txtSearchPageBoot;

/**
 * @author TateLiao
 * @data 2019年6月7日 网站访问路径
 */
@EnableAsync
@Controller
@RequestMapping("/")
public class BaseController {

	@Autowired
	private Environment environment;
	@Autowired
	private QuSearchPageBoot quSearchPageBoot;
	@Autowired
	private W23txtSearchPageBoot w23txtSearchPageBoot;

	@RequestMapping("search/{name}")
	public ModelAndView search(@PathVariable("name") String name) throws Exception {
		ModelAndView modelAndView = new ModelAndView("search");
		List<SearchPage> list = new ArrayList<>();
		Future<List<SearchPage>> quSearchPageFuture = quSearchPageBoot.startCrawt(name);
		Future<List<SearchPage>> w23txtSearchPageFuture = w23txtSearchPageBoot.startCrawt(name);
		list.addAll(quSearchPageFuture.get(6, TimeUnit.SECONDS));
		list.addAll(w23txtSearchPageFuture.get(6, TimeUnit.SECONDS));
		Collections.sort(list, new Comparator<SearchPage>() {
			@Override
			public int compare(SearchPage o1, SearchPage o2) {
				return o2.getLastUpdateTime().compareTo(o1.getLastUpdateTime());
			}
		});
		modelAndView.addObject("list", list);
		modelAndView.addObject("name", name);
		modelAndView.addObject("title", environment.getProperty("website.name"));
		return modelAndView;
	}

}
